(function () {
  'use strict';

  angular
    .module('vboxApp')
    .config(routeConfig)
    .factory('authInterceptor',authInterceptor)
    .run(stateChangeStartWatcher);

  /** @ngInject */
  function routeConfig($stateProvider,jwtInterceptorProvider,$httpProvider) {
    $stateProvider
      .state('login', {
        url: '/login',
        templateUrl: 'app/modules/login/index.html',
        controller:'loginCtrl',

        resolve: {
          loadPlugin: function ($ocLazyLoad) {
            return $ocLazyLoad.load([
            ]);
          }
        }

      });

    jwtInterceptorProvider.tokenGetter = ['$sessionStorage',function($sessionStorage) {
      return $sessionStorage.userToken;
    }];

    $httpProvider.interceptors.push('jwtInterceptor');
    $httpProvider.interceptors.push('authInterceptor');
  }

  function authInterceptor( $q, $sessionStorage,$location) {

    return {
      request: function (config) {
        config.headers = config.headers || {};
        if ($location.url().indexOf('/login')<0 && $sessionStorage.userToken) {
          config.headers.Authorization = 'Bearer ' + $sessionStorage.userToken;
        }
        return config;
      },
      responseError: function(response) {

        if(response.status === 401) {
          delete $sessionStorage.userToken;
          return $q.reject(response);
        }
        else {
          return $q.reject(response);
        }
      }
    };
  }

  function stateChangeStartWatcher($rootScope, $location, jwtHelper, $sessionStorage,authService) {
    $rootScope.$on('$stateChangeStart', function() {

      if (!$sessionStorage.userToken || jwtHelper.isTokenExpired($sessionStorage.userToken)) {
        $location.path('/login');
        // authService.login("avctest","avctest");
      }
    });
  }

})();

